package com.rongshu.view.home.presenter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.rongshu.api.FileUploadService;
import com.rongshu.api.RetorfitService;
import com.rongshu.utils.BitmapUtils;
import com.rongshu.utils.Common;
import com.rongshu.utils.FileUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.BasePresenter;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.home.contract.EditDaySignView;
import com.rongshu.view.home.entity.DaySignDetailsResponse;
import com.rongshu.view.home.entity.MakeDaySignBody;
import com.rongshu.view.userInfo.entity.UpLoadImage;
import com.rongshu.widget.BanyanDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;
import com.widget.toast.ToastUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.functions.Action0;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * created by zhengweis on 2019/2/18.
 * description：
 */
public class EditDaySignPresenter extends BasePresenter<EditDaySignView> {
    private String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    public EditDaySignPresenter(Context context) {
        super(context);
    }

    public void getDaySignInfo(int type, int obj_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("obj_id", obj_id);
        map.put("user_id", UserInfoUtils.getUserId());
        RetorfitService.getDaySignInfo(type, obj_id, UserInfoUtils.getUserId(), Common.encryptionSign(map))
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {

                    }
                })
                .subscribe(new Subscriber<DaySignDetailsResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(DaySignDetailsResponse object) {
                        if (object.getErrCode() == 0 && object.getResponse() != null) {
                            getView().callBackDaySignResponse(object.getResponse());
                        }
                    }
                });
    }

    public void getPicture(final int requestCode) {
        if (!XXPermissions.isHasPermission(mContext, permissions)) {
            XXPermissions.with((Activity) mContext).permission(permissions).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    toGallery(requestCode);
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {

                }
            });
        } else {
            toGallery(requestCode);
        }

    }

    private void toGallery(int requestCode) {
        PictureSelector.create((Activity) mContext)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(true)
                .freeStyleCropEnabled(true)
                .withAspectRatio(4, 3)
                .forResult(requestCode);
    }

    public void bindImg(ImageView imageView, String picPath) {
        Bitmap bitmap = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(picPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap = BitmapFactory.decodeStream(fis);
        //部分Android手机拍照后照片被旋转
        int bitmapDegree = BitmapUtils.getBitmapDegree(picPath);
        if (bitmapDegree != 0) {
            bitmap = BitmapUtils.rotateBitmapByDegree(bitmap, bitmapDegree);
        }
        imageView.setImageBitmap(bitmap);
    }

    /**
     * 单个图片上传
     */
    public void uploadTopImg(String path) {
        long size = 3 * 1024 * 1024;
        //构建要上传的文件
        File file = new File(path);
        try {
            if (FileUtils.getFileSize(file) > size) {
                Luban.with(mContext)
                        .load(file.getAbsolutePath())
                        .ignoreBy(100)
                        .setTargetDir(FileUtils.initPath())
                        .filter(new CompressionPredicate() {
                            @Override
                            public boolean apply(String path) {
                                return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                            }
                        })
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess(File file) {
                                upload(file);
                            }

                            @Override
                            public void onError(Throwable throwable) {

                            }
                        }).launch();
            } else {
                upload(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void upload(File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("AndroidFile", file.getName(), requestFile);
        FileUploadService.upload(body).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).subscribe(new Subscriber<UpLoadImage>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                getView().saveFaild();
            }

            @Override
            public void onNext(UpLoadImage upLoadImageResult) {
                if (upLoadImageResult.getErrCode() == 0) {
                    UpLoadImage.ResponseBean response = upLoadImageResult.getResponse();
                    if (response != null && response.getImgUrl() != null) {
                        String imgUrl = response.getImgUrl().get(0);
                        getView().uploadImgSuccess(imgUrl);
                    } else {
                        ToastUtils.show(upLoadImageResult.getErrMsg());
                    }
                } else {
                    getView().saveFaild();
                    ToastUtils.show(upLoadImageResult.getErrMsg());
                }
            }
        });
    }

    /**
     * 编辑日签
     *
     * @param signId
     * @param dataContent
     * @param aurhor
     * @param imgUrl
     */
    public void editDaySign(int signId, String dataContent, String aurhor, String imgUrl) {
        Map<String, Object> map = new HashMap<>();
        map.put("signMaking_id", signId);
        map.put("user_id", UserInfoUtils.getUserId());
        MakeDaySignBody body = new MakeDaySignBody();
        body.setImgUrl(imgUrl);
        body.setImgExplain("");
        body.setDailyContent(dataContent);
        body.setAuthorName(aurhor);
        RetorfitService.editDaySign(signId, UserInfoUtils.getUserId(),
                Common.encryptionSign(map), body).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).subscribe(new Subscriber<INetBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                getView().saveFaild();
            }

            @Override
            public void onNext(INetBean object) {
                if (object.getErrCode() == 0) {
                    getView().saveDaySignSuccess();
                } else {
                    getView().saveFaild();
                    ToastUtils.show(object.getErrMsg());
                }
            }
        });
    }

    /**
     * 制作日签
     *
     * @param dataContent
     * @param aurhor
     * @param imgUrl
     */
    public void makeDaySign(String dataContent, String aurhor, String imgUrl) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        MakeDaySignBody body = new MakeDaySignBody();
        body.setImgUrl(imgUrl);
        body.setImgExplain("");
        body.setDailyContent(dataContent);
        body.setAuthorName(aurhor);
        RetorfitService.makeDaySign(UserInfoUtils.getUserId(),
                Common.encryptionSign(map), body).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).subscribe(new Subscriber<INetBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                getView().saveFaild();
            }

            @Override
            public void onNext(INetBean object) {
                if (object.getErrCode() == 0) {
                    getView().saveDaySignSuccess();
                } else {
                    getView().saveFaild();
                    ToastUtils.show(object.getErrMsg());
                }
            }
        });
    }

    /**
     * 图片重置大小
     *
     * @param bm
     * @param newWidth
     * @param newHeight
     * @return
     */
    public Bitmap resetBitmapSize(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

    public void showHintDialog() {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(mContext);
        builder.setContent("确定要退出当前日签制作吗");
        builder.setLeft("退出");
        builder.setRight("继续");
        final BanyanDialog dialog = builder.create();
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                getView().finishActivity();
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
